const helper = require("../helper/helper");
const { validate } = require("../utils/validate");
const {
  createWorkService,
  getWorkByTitleService,
  getWorkList,
  updateWorkService,
  deleteWorkService,
  publishWorkService,
  getWorkByIdService,
  copyWorkService,
  createChannelService,
  getChannelListService,
  updateChannelService,
  deleteChannelService,
} = require("../service/workService");
module.exports = {
  //创建作品
  async createWork(req, res) {
    const error = validate(req);
    if (error)
      return helper.errorMessage({
        res,
        error,
        errCode: "createWorkValidateError",
      });
    try {
      const data = await createWorkService(req, req.body);
      return helper.successMessage({ res, data, msg: "创建成功" });
    } catch (error) {
      return helper.errorMessage({ res, error });
    }
  },
  //获取个人作品列表
  async getMyWorkList(req, res) {
    try {
      const { pageIndex, pageSize, title, isTemplate } = req.query;
      const userId = req.info.id;
      const findContion = {
        user: userId,
        ...(title && { title: { $regex: title, $options: "i" } }),
        ...{ isTemplate: isTemplate },
      };
      const findParams = {
        select:
          "id author copiedCount coverImg desc title user isHot createAt isPublic isTemplate content",
        populate: { path: "user", select: "username nickName picture" },
        find: findContion,
        ...(pageIndex && { pageIndex: parseInt(pageIndex) }),
        ...(pageSize && { pageSize: parseInt(pageSize) }),
      };
      const data = await getWorkList(findParams);
      return helper.successMessage({ res, data });
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //获取个人作品列表详情
  async getMyWorkDetail(req, res) {
    try {
      const { id } = req.query;
      const data = await getWorkByIdService(id);
      if (data) {
        return helper.successMessage({ res, data });
      } else {
        return helper.errorMessage({ res, errCode: "workNotExistError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //获取作品详情
  async getWorkDetail(req, res) {
    const error = validate(req);
    if (error)
      return helper.errorMessage({
        res,
        error,
        errCode: "createWorkValidateError",
      });
    try {
      const { id } = req.query;
      const data = await getWorkByIdService(id);
      if (data) {
        return helper.successMessage({ res, data });
      } else {
        return helper.errorMessage({ res, errCode: "workNotExistError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //获取模板作品列表
  async getTemplateWorkList(req, res) {
    try {
      const { pageIndex, pageSize, title, isTemplate } = req.query;
      const findParams = {
        select: "id author copiedCount coverImg desc title user isHot createAt",
        populate: { path: "user", select: "username nickName picture" },
        find: { isPublic: true, isTemplate: true },
        ...(pageIndex && { pageIndex: parseInt(pageIndex) }),
        ...(pageSize && { pageSize: parseInt(pageSize) }),
        ...(title && { title: { $regex: title, $options: "i" } }),
      };
      const data = await getWorkList(findParams);
      return helper.successMessage({ res, data });
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //修改作品
  async updateWork(req, res) {
    try {
      const error = validate(req);
      if (error)
        return helper.errorMessage({
          res,
          errCode: "createWorkValidateError",
        });
      const { id } = req.query;
      const userId = req.info.id;
      const data = await updateWorkService(req, { id, userId, ...req.body });
      if (data) {
        return helper.successMessage({ res, msg: "修改成功", data });
      } else {
        return helper.errorMessage({ res, errCode: "updateWorkError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //删除
  async deleteWork(req, res) {
    try {
      const error = validate(req);
      if (error)
        return helper.errorMessage({
          res,
          errCode: "createWorkValidateError",
        });
      const { id } = req.query;
      const userId = req.info.id;
      const data = await deleteWorkService({ id, userId });
      if (data) {
        return helper.successMessage({ res, msg: "删除成功", data });
      } else {
        return helper.errorMessage({ res, errCode: "deleteWorkError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //发布作品或者模板(isTemplate为true时发布模板)
  async publishWorkOrTemplate(req, res) {
    try {
      const error = validate(req);
      if (error)
        return helper.errorMessage({
          res,
          errCode: "createWorkValidateError",
        });
      const { id, isTemplate, isPublic } = req.body;

      const userId = req.info.id;
      const data = await publishWorkService(
        id,
        { isTemplate, isPublic },
        userId
      );
      if (data) {
        return helper.successMessage({ res, msg: "发布成功", data });
      } else {
        return helper.errorMessage({ res, errCode: "publishWorkError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //复制作品
  async copyWork(req, res) {
    try {
      const { id } = req.query;
      const work = await getWorkByIdService(id);
      if (!work) return helper.errorMessage({ res, errCode: "copyWorkError" });
      if (
        !(work.isTemplate || work.isPublic) &&
        work.user.toString() !== userId
      )
        return helper.errorMessage({ res, errCode: "copyWorkNotPublicError" });
      try {
        const data = await copyWorkService(req, id);
        return helper.successMessage({ res, msg: "复制成功", data });
      } catch (error) {
        return helper.errorMessage({ res });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //创建渠道
  async createChannel(req, res) {
    const error = validate(req);
    if (error) {
      return helper.errorMessage({
        res,
        errCode: "createChannelValidateError",
        error,
      });
    }
    try {
      console.log(req.body);

      const data = await createChannelService(req.body);

      if (data) {
        return helper.successMessage({ res, msg: "创建成功", data });
      } else {
        return helper.errorMessage({ res, errCode: "createChannelError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //获取渠道列表
  async getChannelList(req, res) {
    const { workId } = req.params;
    try {
      const data = await getChannelListService(workId);
      if (data) {
        return helper.successMessage({
          res,
          data: {
            list: data,
            total: data.length,
          },
        });
      } else {
        return helper.errorMessage({ res, errCode: "getChannelListError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //修改渠道名称
  async updateChannelName(req, res) {
    const error = validate(req);
    error &&
      helper.errorMessage({
        res,
        errCode: "updateChannelNameValidateError",
        error,
      });
    try {
      //这个channelId是作品字段中channel数组中每一项的id
      const { channelId } = req.params;
      const { name } = req.body;
      const data = await updateChannelService({ channelId, name });
      if (data) {
        return helper.successMessage({
          res,
          msg: "修改成功",
          data: { channelList: data.channel },
        });
      } else {
        return helper.errorMessage({ res, errCode: "updateChannelNameError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
  //删除渠道信息
  async deleteChannel(req, res) {
    try {
      const { channelId } = req.params;
      const data = await deleteChannelService(channelId);
      if (data) {
        return helper.successMessage({
          res,
          msg: "删除成功",
          data: { channelList: data.channel },
        });
      } else {
        return helper.errorMessage({ res, errCode: "deleteChannelError" });
      }
    } catch (error) {
      return helper.errorMessage({ res });
    }
  },
};
